package top.ddltech.algorithm.sort;

import top.ddltech.algorithm.util.SortUtil;

/**
 * 希尔排序
 */
public class ShellSort {

    /**
     * 将a[]按升序排列
     *
     * @param a 数组
     */
    public static void sort(Comparable[] a) {
        int N = a.length;
        int h = 1;
        // 1, 4, 13, 40, 121, 364, 1093, ...
        while (h < N / 3) {
            h = 3 * h + 1;
        }
        while (h >= 1) {
            // 将数组变为h有序
            for (int i = h; i < N; i++) {
                // 将a[i]插入到a[i-h]、a[i-2*h]、a[i-3*h]...之中
                Comparable tmp = a[i];
                int j = i;
                for (; j >= h && SortUtil.less(tmp, a[j - h]); j -= h) {
                    a[j] = a[j - h];
                }
                a[j] = tmp;
            }
            h = h / 3;
        }
    }
}
